package com.springmongodb.controller;

import com.springmongodb.pojo.Book;
import com.springmongodb.respository.BookRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class BookController {
	@Resource
	private BookRepository bookRepository;
	@GetMapping("/books")
	public String books(Model model){
		model.addAttribute("books",bookRepository.findAll());
		return "books";
	}
	@GetMapping("/book/{id}")
	public String findStudentById(@PathVariable("id") Integer id, Model model){
		model.addAttribute("book",bookRepository.findById(id).orElse(new Book()));
		return "book";
	}
	@GetMapping("/addBook")
	public String addBook(){
		return "addBook";
	}
	@PostMapping("/addBook")
	public String addStudent(Book book){
		bookRepository.insert(book);
		return "redirect:books";
	}
	@GetMapping("/deleteBook/{id}")
	   public String deleteBook(@PathVariable("id") Integer id){
	      bookRepository.deleteById(id);
	      return "redirect:/books";
	   }
	@GetMapping("/updateBook/{id}")
	public String toUpdateStudent(@PathVariable Integer id,Model model){
		Book book = bookRepository.findById(id).orElse(new Book());
		model.addAttribute("book",book);
		return "updateBook";
	}
	@PostMapping("/updateBook")
	public String UpdateBook(Book book){
		bookRepository.save(book);
		return "redirect:books";
	}
	@GetMapping("/findByAuthor")
	public String findByAuthor(String author,Model model){
		model.addAttribute("books",bookRepository.findByAuthor(author));
		return "books";
	}
	@GetMapping("/findByCategoryAndAuthor")
	public String findCategoryAndAuthor(String category,String author,Model model){
		model.addAttribute("books",bookRepository.findByCategoryAndAuthor(category,author));
		return "books";
	}
	@GetMapping("/findByPriceBetween")
	public String findByPriceBetween(double min,double max,Model model){
		model.addAttribute("books",bookRepository.findByPriceBetween(min,max));
		return "books";
	}
	@GetMapping("/findByNameLike")
	public String findByNameLike(String name,Model model){
		model.addAttribute("books",bookRepository.findByNameLike(name));
		return "books";
	}
	@GetMapping("/findCategory")
	public String findByPriceAndCategory(String category,Model model){
		model.addAttribute("books",bookRepository.findCategory(category));
		return "books";
	}
	@GetMapping("/findPrice")
	public String findPrice(double price,Model model){
		model.addAttribute("books",bookRepository.findPrice(price));
		return "books";
	}
	@GetMapping("/searchBooks")
	public String searchBooks(String name,String category,Model model){
		model.addAttribute("books",bookRepository.searchBooks(name,category));
		return "books";
	}
}
